<?php
// +----------------------------------------------------------------------
// | sfadmin - Suifeng Administration
// +----------------------------------------------------------------------
// | Copyright (c) 2017-2020 http://suifeng.tech All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: suifeng <1787585212@qq.com>
// +----------------------------------------------------------------------

namespace app\admin\controller;

use app\admin\common\AdminController;
use app\admin\common\AdminException;

class Group extends AdminController
{
    public function index()
    {
        $data = $this->_get_pagination_data();

        $data['total_rows'] = model('admin/group')->query_count($data['where_list']);
        $data['page_count'] = intval(ceil($data['total_rows'] / $data['page_size']));
        $data['page_num'] = $data['page_num'] > $data['page_count'] ? 1 : $data['page_num'];

        $data['group_list'] = model('admin/group')->query_list($data['where_list'], $data['page_num'], $data['page_size'], $data['sort_field'], $data['sort_order']);

        $this->display('group/group_list', $data);
    }

    public function create()
    {
        $group_info = model('admin/group')->initDefault();

        if (request()->isPost()) {
            $group_info->acceptData($this->post_array());

            try {
                $group_info->save();
            } catch (AdminException $ae) {
                $this->error($ae->getString());
            }

            $this->success('新增成功。', $this->url('index'));
        }

        $this->assign('group_info', $group_info);
        $this->display('group/group_form');
    }

    public function modify($id)
    {
        $group_info = model('admin/group')->findOrFail($id);

        if (request()->isPost()) {
            $group_info->acceptData($this->post_array());

            try {
                $group_info->save();
            } catch (AdminException $ae) {
                $this->error($ae->getString());
            }

            $this->success('修改成功。', $this->url('index'));
        }

        $this->assign('group_info', $group_info);
        $this->display('group/group_form');
    }

    public function bulk_delete($ids = array())
    {
        $group_list = model('admin/group')->where('id', 'in', $ids)->select();

        foreach ($group_list as $group_info) {
            if ($group_info['id'] == ADMIN_SUPER_GROUP_ID) {
                $this->error('管理员组不允许删除。');
            }
        }

        foreach ($group_list as $group_info) {
            try {
                $group_info->delete();
            } catch (AdminException $ae) {
                $this->error($ae->getString());
            }
        }

        $this->success('删除成功。', $this->url('index'));
    }
}